#include "server.h"

Server::Server(QObject *parent, quint16 port) : QTcpServer(parent)
{
    listen(QHostAddress::AnyIPv4, port);
    connect(this, SIGNAL(newConnection()), SLOT(slotAccept()));
}

Server::~Server()
{

}

void Server::slotAccept()
{
    qDebug() << "newConnection";
}

void Server::incomingConnection(qintptr socket)
{
    qDebug() << "incomingConnection";
    TcpSocket *client = new TcpSocket();
    client->setSocketDescriptor(socket);

    //connect(client, SIGNAL(readyRead()),this, SLOT(slotReadData()));
    connect(client, SIGNAL(disconnected(int)),
            this, SLOT(slotDisconnected(int)));
    connect(client, SIGNAL(updateMsg(QByteArray)),
            this, SLOT(slotUpdate(QByteArray)));

    clients << client;
}

/*
void Server:: slotReadData()
{
    foreach (TcpSocket *c, clients) {
        //qDebug() << c->bytesAvailable();
        while(c->bytesAvailable() > 0){
            QByteArray datagrame;
            datagrame.resize(c->bytesAvailable());
            c->read(datagrame.data(), datagrame.size());

            foreach (QTcpSocket *cli, clients) {
                cli->write(datagrame);
            }

            qDebug() << datagrame.data();
        }
    }
}
*/

void Server::slotDisconnected(int socketDescrip)
{
    qDebug() << "disconnect client : " << socketDescrip;
    foreach (TcpSocket *c, clients) {
        if(c->socketDescriptor() == socketDescrip)
            clients.removeOne(c);
        return;
    }
}

void Server::slotUpdate(QByteArray datagram)
{
    foreach (TcpSocket *c, clients) {
        c->write(datagram);
    }
    emit updateMsg(datagram);
}
